package com.sczmgk.hotline.httpUtils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Base64;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.http.client.multipart.HttpMultipartMode;
import com.lidroid.xutils.http.client.multipart.MultipartEntity;
import com.lidroid.xutils.http.client.multipart.content.ContentBody;
import com.lidroid.xutils.http.client.multipart.content.FileBody;
import com.lidroid.xutils.http.client.multipart.content.StringBody;
import com.sczmgk.hotline.MyApp;
import com.sczmgk.hotline.callback.ParseJsonCallback;
import com.sczmgk.hotline.constant.Constant;
import com.sczmgk.hotline.des.Des3;
import com.sczmgk.hotline.des.SessionKeyBean;
import com.sczmgk.hotline.entity.base.BaseEntity;
import com.sczmgk.hotline.utils.CacheUtils;
import com.sczmgk.hotline.utils.MyLog;
import com.sczmgk.hotline.utils.Tools;

import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.sczmgk.hotline.MyApp.httpUtils;


/**
 * Created by Administrator on 2017/3/8.
 */

public class MyHttp {
    private static final boolean isOld = false;

    private static final String TAG = MyHttp.class.getSimpleName();

    /**
     * 返回的结果没有错误
     */
    public static final int NO_ERROR = 0;

    public static final int GET = 1;
    public static final int POST = 2;
    public static final int UPLOAD_FILE = 3;
    private static HttpHandler<String> handler;

    /**
     * 上传文件及表单数据
     *
     * @param context
     * @param filePath          文件路径集合
     * @param url
     * @param dataMap           表单数据集合
     * @param fileType          文件类型数据集合
     * @param parseJsonCallback
     */
    public static void uploadFile(Context context, List<String> filePath, String url, Map<String, Object> dataMap, Map<String, Object> fileType, ParseJsonCallback parseJsonCallback) {
        request(context, filePath, url, null, dataMap, fileType, UPLOAD_FILE, false, null, parseJsonCallback);
    }

    /**
     * 单上传文件
     *
     * @param context
     * @param filePath
     * @param url
     * @param fileType
     * @param parseJsonCallback
     */
    public static void uploadFile(Context context, List<String> filePath, String url, Map<String, Object> fileType, ParseJsonCallback parseJsonCallback) {
        request(context, filePath, url, null, null, fileType, UPLOAD_FILE, false, null, parseJsonCallback);
    }

    /**
     * @param context
     * @param url
     * @param dataMap           原数据 map
     * @param reqType           请求类型
     * @param isNeedCache       是否需要缓存
     * @param cacheKey          url+type
     * @param parseJsonCallback
     */
    public static void request(Context context, final String url, final Map<String, Object> dataMap, final int reqType, final boolean isNeedCache, final String cacheKey,
                               final ParseJsonCallback parseJsonCallback) {
        request(context, null, url, null, dataMap, null, reqType, isNeedCache, cacheKey, parseJsonCallback);
    }

    /**
     * @param context
     * @param filePath
     * @param url
     * @param dataMap           原数据 map
     * @param reqType           请求类型
     * @param isNeedCache       是否需要缓存
     * @param cacheKey          url+type
     * @param parseJsonCallback
     */
    private static void request(Context context, List<String> filePath, final String url, String rawJson, final Map<String, Object> dataMap, final Map<String, Object> fileType, final int reqType, final boolean isNeedCache, final String cacheKey,
                                final ParseJsonCallback parseJsonCallback) {
        MyLog.i(TAG, "rawJson :" + rawJson);
        String encodeJson = "";

        if (MyApp.sessionKey != null) {
            MyLog.d(TAG, "已获取到密钥");
            //1.map提交
            //2.json提交
            if (!Tools.isEmpty(rawJson)) {
                encodeJson = encodeDataByJson(rawJson);
            } else {
                //4.加密data
                encodeJson = encodeDataByMap(dataMap);
            }

            //请求数据
            //TODO okHttp
            requestData(context, filePath, url, rawJson, encodeJson, dataMap, fileType, reqType, isNeedCache, cacheKey, parseJsonCallback);
        } else {
            requestBySessionKey(context, filePath, url, rawJson, dataMap, fileType, reqType, isNeedCache, cacheKey, parseJsonCallback);
        }
    }


    public static void reportException(String url, Map<String, Object> dataMap) {


        String enCodeDataStr = getDataJson(dataMap).toString();
        requestData(null, null, url, null, enCodeDataStr, null, null, POST, false, null, null);
    }

    public static void cancle() {
        if (handler != null) {
            handler.cancel();
            handler = null;
        }
    }

    /**
     * @param context
     * @param filePath
     * @param url
     * @param rawJson           未加密的Json字符串
     * @param encodeJson        加密后的Json
     * @param dataMap
     * @param fileType
     * @param reqType
     * @param isNeedCache
     * @param cacheKey
     * @param parseJsonCallback
     */
    private static void requestData(final Context context, final List<String> filePath, final String url, final String rawJson, final String encodeJson, final Map<String, Object> dataMap, final Map<String, Object> fileType, final int reqType, final boolean isNeedCache, final String cacheKey,
                                    final ParseJsonCallback parseJsonCallback) {
        handler = null;
        RequestParams params = new RequestParams("UTF-8");
        params.setHeader("Cache-Control", "no-cache");
        params.setHeader("Pragrma", "no-cache");
        params.setHeader("expires", "0");
        switch (reqType) {
            case GET:

                break;
            case POST:
                setParams(params, encodeJson);
                MyLog.d(TAG, "请求的URL: " + url);
                MyLog.i(TAG, "请求的json串： " + encodeJson);
                handler = httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        //解析数据
                        String result = responseInfo.result;
                        try {
                            paseJson(result, context, filePath, url, rawJson, dataMap, fileType, reqType, isNeedCache, cacheKey, parseJsonCallback);
                        } catch (IOException e) {
                            e.printStackTrace();
                            MyLog.e(TAG, "解析JsoN错误");
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        if (parseJsonCallback != null) {
                            MyLog.e(TAG, "服务器错误-- 错误码： " + error.getExceptionCode() + "   msg: " + msg);
                            parseJsonCallback.onServerUnKnownError();
                        }
                    }
                });
                break;
            case UPLOAD_FILE:
                //1.Base64加密图片信息
                MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT, null, Charset.forName(HTTP.UTF_8));
                setMultipart(params, multipartEntity, dataMap, filePath, fileType);
                MyLog.d(TAG, "请求的URL: " + url);
                MyLog.i(TAG, "请求的json串： " + encodeJson);
                httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        //解析数据

                        String result = responseInfo.result;
                        try {
                            paseJson(result, context, filePath, url, rawJson, dataMap, fileType, reqType, isNeedCache, cacheKey, parseJsonCallback);
                        } catch (IOException e) {
                            e.printStackTrace();
                            MyLog.e(TAG, "解析JsoN错误");
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        if (parseJsonCallback != null) {
                            MyLog.e(TAG, "服务器错误-- 错误码： " + error.getExceptionCode() + "   msg: " + msg);
                            parseJsonCallback.onServerUnKnownError();
                        }
                    }
                });
                break;


        }

    }

    private static void setMultipart(RequestParams params, MultipartEntity multipartEntity, Map<String, Object> dataMaps, List<String> filePath, Map<String, Object> fileType) {

        String encodeJson;
        try {
            JSONObject dataJsonData = null;
            JSONObject fileTypeJsonData = null;

            if (dataMaps != null) {

                dataJsonData = getDataJson(dataMaps);
            }
            if (fileType != null) {

                fileTypeJsonData = getDataJson(fileType);
            }

            JSONObject jo = new JSONObject();
            jo.put("filetypekey", fileTypeJsonData);
            jo.put("filedatakey", dataJsonData);
            String toString = jo.toString();
            String requestJson = getRequestJson(toString, false);
            MyLog.d(TAG, "文件上传信息：" + requestJson);
            encodeJson = Base64.encodeToString(requestJson.getBytes("utf-8"), Base64.NO_WRAP).trim();// 自定义Base64lNo_WRAP是设置base64字符串里没有换行符

            ContentBody contentBody = new StringBody(encodeJson);
            multipartEntity.addPart("datas", contentBody);

            for (String s : filePath) {
                MyLog.i(TAG, "filePath: " + s);
                if (s != null) {
                    File file = new File(s);
                    String[] split = s.split("/");
                    String fileName = split[split.length - 1];
                    FileBody file2 = new FileBody(file);

                    multipartEntity.addPart(fileName, file2);
                }
            }

            params.setBodyEntity(multipartEntity);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void paseJson(String response, Context context, List<String> filePath, String url, String rawJson, Map<String, Object> dataMap, Map<String, Object> fileType, int reqType, boolean isNeedCache, String cacheKey, ParseJsonCallback parseJsonCallback) throws IOException {
        parseBaseJson(context, response, filePath, url, rawJson, dataMap, fileType, reqType, isNeedCache, cacheKey, parseJsonCallback);
    }

//    /**
//     * 添加text表单part
//     *
//     * @param multipartBuilder
//     * @param dataMaps
//     * @param fileType
//     */
//    private static void addStringParts(MultipartBuilder multipartBuilder, Map<String, Object> dataMaps, Map<String, Object> fileType) {
//
//        String encodeJson = null;
//        try {
//            JSONObject dataJsonData = null;
//            JSONObject fileTypeJsonData = null;
//
//            if (dataMaps != null) {
//
//                dataJsonData = getDataJson(dataMaps);
//            }
//            if (fileType != null) {
//
//                fileTypeJsonData = getDataJson(fileType);
//            }
//            JSONObject jo = new JSONObject();
//            jo.put("filetypekey", fileTypeJsonData);
//            jo.put("filedatakey", dataJsonData);
//            String toString = jo.toString();
//            String requestJson = getRequestJson(toString, false);
//            MyLog.d(TAG, "文件上传信息：" + requestJson);
//            encodeJson = Base64.encodeToString(requestJson.getBytes("utf-8"), Base64.NO_WRAP).trim();// 自定义Base64lNo_WRAP是设置base64字符串里没有换行符
//            RequestBody dataBody = RequestBody.create(MEDIA_FROM_DATA, encodeJson);
//            multipartBuilder.addPart(Headers.of("Content-Disposition", "form-data; name=\"datas\""), dataBody);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }


//    /**
//     * 加入文件
//     *
//     * @param multipartBuilder
//     * @param filePath
//     */
//    private static void addFileParts(MultipartBuilder multipartBuilder, List<String> filePath) {
//        for (String s : filePath) {
//            if (s != null) {
//                File file = new File(s);
//                String[] split = s.split("/");
//                String fileName = split[split.length - 1];
//                RequestBody fileBody = RequestBody.create(MEDIA_OBJECT_STREAM, file);
//                multipartBuilder.addPart(Headers.of("Content-Disposition", "form-data;filename=" + fileName + ""), fileBody);
//            }
//        }
//    }


    private static void requestBySessionKey(final Context context, final List<String> filePath, final String url, final String rawJson, final Map<String, Object> dataMap, final Map<String, Object> fileType, final int reqType, final boolean isNeedCache, final String cacheKey, final ParseJsonCallback parseJsonCallback) {

        getSessionKey(new onGetSessionKeyCallback() {
            @Override
            public void onGetSessionKey() {
                MyLog.i(TAG, "取密钥回调");
                //5.正常请求
                request(context, filePath, url, rawJson, dataMap, fileType, reqType, isNeedCache, cacheKey, parseJsonCallback);
            }

            @Override
            public void onGetSessionKeyError() {
                if (parseJsonCallback != null) {
                    parseJsonCallback.onServerUnKnownError();
                }
            }
        });
    }

    /**
     * 把集合转换为通用Json格式(context,data,verify,type)
     *
     * @param dataMap
     * @return
     */
    private static String encodeDataByMap(Map<String, Object> dataMap) {

        //将Map集合转换为Json字符串
        String dataJson = getDataJson(dataMap).toString();
        MyLog.i(TAG, "原数据 -->：" + dataJson);
        String requestJson = getRequestJson(dataJson, false);

        return requestJson;
    }

    /**
     * 把Json转换为通用Json格式(context,data,verify,type)
     *
     * @param jsonStr
     * @return
     */
    private static String encodeDataByJson(String jsonStr) {

        MyLog.i(TAG, "原数据 -->：" + jsonStr);
        String requestJson = getRequestJson(jsonStr, false);

        return requestJson;
    }


    /**
     * 解析数据
     *
     * @param resultData
     * @param parseJsonCallback
     */
    private static void parseBaseJson(final Context context, String resultData, final List<String> filePath, final String url, final String rawJson, final Map<String, Object> dataMap, final Map<String, Object> fileType, final int reqType, final boolean isNeedCache, final String cacheKey, final ParseJsonCallback parseJsonCallback) {

        MyLog.d(TAG, "返回的数据------->>>: " + resultData);
        Gson gson = new Gson();
        BaseEntity baseEntity = null;
        try {

            baseEntity = gson.fromJson(resultData, BaseEntity.class);
        } catch (Exception e) {
            MyLog.e(TAG, "解析BaseEntity 错误 ！");
        }

        if (parseJsonCallback == null) {
            return;
        }

        if (baseEntity == null) {
            return;
        } else {
            int code = baseEntity.code;

            String verify = baseEntity.verify;
            String dataEncodeStr = baseEntity.data;
            String msg = baseEntity.msg;
            //1.没有错误   1
            //2.密钥失效   8001
            //3.有错误     0
            switch (code) {
                case 1://请求成功
                    // 处理正常逻辑
                    // 1.判断verify是否为空:如获取手机验证码是不要返回data的
                    if (TextUtils.isEmpty(verify)) {
                        // 是空，处理成功的逻辑，如提示获取验证码成功
                        parseJsonCallback.onVerifyIsNull();
                        MyLog.d(TAG, "请求成功，不需要返回数据！");
                    } else {
                        MyLog.d(TAG, "sessionKey: " + MyApp.sessionKey + "   md5：　　" + verify);

                        // 验证成功，解析数据 获取解密后的数据
                        String dataRaw = MyHttp.getDataRaw(dataEncodeStr);

                        String verify2 = MyHttp.encrypt(dataRaw);
                        MyLog.d(TAG, "md51 :" + verify + "      md52 :" + verify2);

                        // 3.判断
                        if (verify.equals(verify2)) {
                            MyLog.d(TAG, "验证MD5成功,回调字符串是 ：" + dataRaw.toString());
                            //TODO 缓存数据
                            if (isNeedCache) {

                                cacheData(context, cacheKey, dataRaw);
                            }
                            parseJsonCallback.onVerifySuccess(dataRaw);

                        } else {
                            // 提示错误信息
                            parseJsonCallback.onServerUnKnownError();
                            MyLog.e(TAG, "MD5验证失败！！！！！！！！！！！！！！！！");
                        }
                    }
                    break;
                case 8001:
                    //请求密钥
                    getSessionKey(new onGetSessionKeyCallback() {
                        @Override
                        public void onGetSessionKey() {
                            //获取到密钥,重新访问
                            request(context, filePath, url, rawJson, dataMap, fileType, reqType, isNeedCache, cacheKey, parseJsonCallback);
                        }

                        @Override
                        public void onGetSessionKeyError() {
                            MyLog.e(TAG, "服务器未知错误 2 ");
                            //未获取到密钥
                            parseJsonCallback.onServerUnKnownError();
                        }
                    });
                    break;
                default:
                    parseJsonCallback.onErrorCodeError(msg);
                    MyLog.e(TAG, "服务器错误------> 错误信息：" + msg);
                    break;
            }

        }
    }


    /**
     * 缓存数据
     *
     * @param tag
     * @param data
     */
    private static void cacheData(Context context, String tag, String data) {

        //TODO　是否需要加密
        //缓存数据
        String cacheKey = getCacheTag(context, tag);
        if (!Tools.isEmpty(cacheKey)) {

            CacheUtils.cacheStringData(context, cacheKey, data);
        }
    }

    public static String getCacheTag(Context context, String cacheKey) {
        return cacheKey;
    }

    /**
     * 取得请求数据的公共方法(1.context 2.加密后的data )
     *
     * @param data            未加密的Data数据
     * @param isGetSessionKey 是否为取会话密钥
     * @return json请串原数据
     */
    private static String getRequestJson(String data, boolean isGetSessionKey) {
        String result = "";
        String sessionKey;
        if (isGetSessionKey) {
            MyApp.type = 0;
            sessionKey = Constant.SERVICE_PUBLIC_KEY;
        } else {
            sessionKey = MyApp.sessionKey;
        }
        JSONObject param = new JSONObject();
        try {
            JSONObject context = getContextJson();
            param.put("context", context);
            String encedeData = Des3.des3EncodeECB(sessionKey, data);
            param.put("data", encedeData);
            param.put("verify", encrypt(data));
            param.put("type", MyApp.type);
            result = param.toString();
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * 取得Context的数据
     *
     * @return context 返回 json 对象
     */
    private static JSONObject getContextJson() {
        String imei = MyApp.imei;
        String imsi = MyApp.imsi;
        int userid = MyApp.loginUserUid;
        JSONObject result = null;
        JSONObject param = new JSONObject();
        try {
            param.put("imei", imei);
            param.put("imsi", imsi);
            param.put("uid", ((userid == 0 || userid == -1) ? 0 : userid));
            result = param;
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * 设置请求参数post,put
     *
     * @param params
     * @param requestJson
     */
    private static void setParams(RequestParams params, String requestJson) {
        try {
            params.setContentType("application/json");
            StringEntity stringEntity = new StringEntity(requestJson, "UTF-8");
            params.setBodyEntity(stringEntity);
        } catch (UnsupportedEncodingException e) {
            MyLog.e(TAG, e.getMessage());
            e.printStackTrace();
        }
    }

    private static void getSessionKey(final onGetSessionKeyCallback getSessionKeyCallback) {

        MyLog.d(TAG, "取密钥URL: " + Constant.BASE_URL + Constant.POST_SESSIONKEYS_URL);
        //获取会话密钥data json 原数据
        String data = getSessionKeyDataJson();
        //获取Json字符串（包含Context，imei,imsi...）
        final String requestJsonData = getRequestJson(data, true);
        MyLog.d(TAG, "获取密钥 加密Data后的Json字符串 : " + requestJsonData);
        RequestParams params = new RequestParams("UTF-8");
        params.setHeader("Cache-Control", "no-cache");
        params.setHeader("Pragrma", "no-cache");
        params.setHeader("expires", "0");
        setParams(params, requestJsonData);
        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.BASE_URL + Constant.POST_SESSIONKEYS_URL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                String result = responseInfo.result;
                MyLog.i(TAG, "密钥原始数据：" + result);

                Gson gson = new Gson();
                BaseEntity responseBean = null;
                try {
                    responseBean = gson.fromJson(result, BaseEntity.class);

                } catch (Exception e) {
                    MyLog.e(TAG, "取会话空密钥返回的Json解析错误！");
                }
                if (responseBean == null) {
                    return;
                }
                try {
                    // 取到加密的data
                    String encodeSessionKey = responseBean.data;
                    // 取出解密后的data原数据,用随机码解密
                    String rawData = Des3.des3DecodeECB(MyApp.randomCode, encodeSessionKey);
                    // MD5 data原数据
                    String dataMD5 = encrypt(rawData);
                    // 对比服务器传过来的原数据
                    if (!dataMD5.equals(responseBean.verify)) {
                        MyLog.e(TAG, "data MD5 验证错误 ！");
                        return;
                    }
                    MyLog.d(TAG, "会话密钥 解密后的原数据 : " + rawData);
                    Gson gsonSessionKey = new Gson();
                    SessionKeyBean sessionKeyBean = gsonSessionKey.fromJson(rawData, SessionKeyBean.class);
                    String sessionKey = sessionKeyBean.sessionpwd;
                    String token = sessionKeyBean.token;
                    MyLog.d(TAG, "取到了会话密钥：" + sessionKey);
                    // 存入会话密钥
                    MyApp.sessionKey = sessionKey;
                    MyApp.token = token;
                    // 2.将type设置成 1
                    MyApp.type = 1;
                    String exptime = sessionKeyBean.exptime;
                    MyLog.d(TAG, "密钥过期时间：" + exptime);
                    if (getSessionKeyCallback != null) {
                        getSessionKeyCallback.onGetSessionKey();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {
                MyLog.e(TAG, "服务器错误-- 错误码： " + error.getExceptionCode() + "   msg: " + msg);
                if (getSessionKeyCallback != null) {
                    getSessionKeyCallback.onGetSessionKeyError();
                }
            }
        });
    }

    /**
     * 下载文件 的方法
     *
     * @param url
     * @param target   存储位置
     * @param callback
     */
    public static void downloadFile(String url, String target, RequestCallBack<File> callback) {
        MyLog.d(TAG, "下载图片的URL: " + url + "    目标路径: " + target);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.download(url, target, callback);
    }

    private void addPart(List<String> filePath) {


    }

    /**
     * 取得正常请求的解密json原串
     *
     * @param dataEncodeStr
     * @return
     */
    private static String getDataRaw(String dataEncodeStr) {

        String rawData = Des3.des3DecodeECB(MyApp.sessionKey, dataEncodeStr);
        return rawData;
    }

    /**
     * 生成获取会话密钥data原数据
     *
     * @return 未加密的json字符串
     */
    private static String getSessionKeyDataJson() {
        String result = "";
        String imei = MyApp.imei;
        JSONObject param = new JSONObject();
        try {
            param.put("imei", imei);
            String randomCode = getRandomCode();
            MyApp.randomCode = randomCode;
            param.put("randomcode", randomCode);
            result = param.toString();
        } catch (Exception e) {
            MyLog.e(TAG, "生成取密钥的data原字符串错误");
        }
        MyLog.d(TAG, "获取密钥 data字符串 : " + result);
        return result;
    }

    /**
     * 生成24位数字的随机数作为id
     *
     * @return 24位的随机码： 5d2fd5564155414564212sa
     */
    public static String getRandomCode() {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-", "");
        return uuid.substring(0, 24);
    }


    /**
     * 取得会话密钥的回调接口
     */
    public interface onGetSessionKeyCallback {
        /**
         * 取得会话密钥时回调
         */
        void onGetSessionKey();

        /**
         * 取会话密钥错误回调
         */
        void onGetSessionKeyError();
    }

    /**
     * 生成请求的Data原数据
     *
     * @param dataMaps 数据集合
     * @return json字符串
     */
    private static JSONObject getDataJson(Map<String, Object> dataMaps) {
        JSONObject result = null;
        JSONObject param = new JSONObject();
        if (dataMaps != null) {
            try {
                for (Map.Entry<String, Object> entry : dataMaps.entrySet()) {
                    if (entry.getKey().equals("file")) {
                        param.put("file", new File((String) entry.getValue()));

                    }
                    {
                        param.put(entry.getKey(), entry.getValue());
                    }
                }
                result = param;

            } catch (Exception e) {
                MyLog.e(TAG, "生成请求Data的json原字符串 错误！！");
            }
        } else {
            result = new JSONObject();
        }
        return result;
    }


    public static void requestFromJson(Context context, String url, String rawJson, int requestType, ParseJsonCallback parseJsonCallback) {

        request(context, null, url, rawJson, null, null, requestType, false, null, parseJsonCallback);
    }


    /**
     * MD5加密
     *
     * @param plaintext 明文
     * @return ciphertext 密文
     */
    public final static String encrypt(String plaintext) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] btInput = plaintext.getBytes("utf-8");
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return "error";
        }
    }

}
